package com.example.test_flutter.channel

import android.os.Bundle
import android.util.Log
import android.view.KeyEvent
import android.view.Window
import androidx.appcompat.app.AppCompatActivity
import com.atom.module.logger.Logger
import com.example.test_flutter.BuildConfig
import com.example.test_flutter.R
import io.flutter.embedding.android.FlutterFragment
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.*

class EventChannelActivity : AppCompatActivity() {

    lateinit var flutterFragment: FlutterFragment

    override fun onCreate(savedInstanceState: Bundle?) {
        supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // 跳转到flutter
        val createDefault = FlutterFragment.createDefault()
        val beginTransaction = supportFragmentManager.beginTransaction()
        beginTransaction.add(R.id.fragmentLayout, createDefault)
        beginTransaction.commit()
        flutterFragment = createDefault
    }

    val Method_Channel = "com.example.flutter_test_call/methodChannel"
    var eventSink: EventChannel.EventSink? = null
    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {
            flutterFragment.flutterEngine?.apply {
                val eventChannel = EventChannel(this.dartExecutor.binaryMessenger, Method_Channel)
                Logger.e("EventChannel >>>")
                eventChannel.setStreamHandler(object : EventChannel.StreamHandler {
                    override fun onListen(arguments: Any?, events: EventChannel.EventSink?) {
                        Logger.e("onListen", arguments)
                        eventSink = events
                        events?.success("开始接收")
                    }

                    override fun onCancel(arguments: Any?) {
                        Logger.e("onCancel", arguments)
                        eventSink = null
                    }
                })
            }
        }

        if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
            eventSink?.success("KEYCODE_VOLUME_UP >>> ${System.currentTimeMillis()}")
        }
        return super.onKeyDown(keyCode, event)
    }

}